// pages/my/songSheet/songSheet.js
/*
const bgm = wx.getBackgroundAudioManager();
bgm.title = '主角'
bgm.epname = '主角'
bgm.singer = '马里奥'
bgm.coverImgUrl = 'http://y.gtimg.cn/music/photo_new/T002R300x300M000000PKt1K05D3I8.jpg'
// 设置了 src 之后会自动播放
bgm.src = 'https://6c69-ling-prod-5gjoecyq23b768be-1300335304.tcb.qcloud.la/music/%E4%B8%BB%E8%A7%92%20-%20%E9%A9%AC%E9%87%8C%E5%A5%A5.m4a?sign=c193a9f47fbcdce0445fd3c044fc72a9&t=1643247308'
*/
// import data from "../../../utils/musicData.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    playStatus: false,
    audioIndex: -1,//如果直接播放则改为对应下标
    progress: 0,
    duration: 0,
    audioList: [],
    showList: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({audioList: data})
    //初始化时默认不播放
    // this.playMusic();
    this.getSongSheet()
  },
  // 查询歌单列表
  getSongSheet() {
    let timestamp = Date.parse(new Date());
    let expiration = wx.getStorageSync("songSheetExpiration");
    let songSheetList = wx.getStorageSync("songSheetList")
    if(expiration > timestamp && songSheetList){
      console.log("songSheetList数据未过期继续使用缓存数据~");
      this.setData({ audioList: songSheetList });
      return;
    }
    this.setData({showLoading: true});
    wx.cloud.callFunction({
      name: "query",
      data: {
        dbName: "t_song",
        // 查询条件
        filter: {},
      },
      success: (res) => {
        this.loadModal()
        console.log("查询歌单列表回调：", res)
        this.setData({ audioList: res.result.data });
        // 放入缓存，异步不会阻塞当前任务
        wx.setStorage({data: res.result.data,key: 'songSheetList'})
        // 有效期24小时，1分钟=60000ms
        let expiration = Date.parse(new Date()) + (24 * 60 * 60000)
        wx.setStorage({data: expiration,key: 'songSheetExpiration'})
      },
      fail: (error) => {
        this.setData({ showLoading: false });
        wx.showToast({
          title: '查询失败',
          icon: 'none',
          duration: 2000, //单位ms，默认1500
          mask: true
        });
      }
    })
  },

  /**
   * loading加载1s后关闭
   */
  loadModal() {
    this.setData({ showLoading: true });
    setTimeout(() => {
      this.setData({
        showLoading: false
      })
    }, 1000)
  },

  playMusic: function () {
    let audio = this.data.audioList[this.data.audioIndex];
    let manager = wx.getBackgroundAudioManager();
    manager.title = audio.name || "音频标题";
    manager.epname = audio.epname || "专辑名称";
    manager.singer = audio.author || "歌手名";
    manager.coverImgUrl = audio.poster;
    // 设置了 src 之后会自动播放
    manager.src = audio.src;
    manager.currentTime = 0;
    let that = this;
    manager.onPlay(function () {
      // console.log("======onPlay======");
      that.setData({
        playStatus: true
      })
      that.countTimeDown(that, manager);
    });
    manager.onPause(function () {
      that.setData({
        playStatus: false
      })
      console.log("======onPause======");
    });
    manager.onEnded(function () {
      console.log("======onEnded======");
      that.setData({
        playStatus: false
      })
      setTimeout(function () {
        that.nextMusic();
      }, 1500);
    });
  },

  //循环计时
  countTimeDown: function (that, manager, cancel) {
    if (that.data.playStatus) {
      setTimeout(function () {
        if (that.data.playStatus) {
          // console.log("duration: " + manager.duration);
          // console.log(manager.currentTime);
          that.setData({
            progress: Math.ceil(manager.currentTime),
            progressText: that.formatTime(Math.ceil(manager.currentTime)),
            duration: Math.ceil(manager.duration),
            durationText: that.formatTime(Math.ceil(manager.duration))
          })
          that.countTimeDown(that, manager);
        }
      }, 1000)
    }
  },

  //拖动事件
  sliderChange: function (e) {
    let manager = wx.getBackgroundAudioManager();
    manager.pause();
    manager.seek(e.detail.value);
    this.setData({
      progressText: this.formatTime(e.detail.value)
    })
    setTimeout(function () {
      manager.play();
    }, 1000);
  },

  //列表点击事件
  listClick: function (e) {
    let pos = e.currentTarget.dataset.pos;
    if (pos != this.data.audioIndex) {
      this.setData({
        audioIndex: pos,
        showList: false
      })
      this.playMusic();
    } else {
      this.setData({
        showList: false
      })
      //更改播放状态
      this.playOrpause();
    }
  },

  //上一首
  lastMusic: function () {
    let audioIndex = this.data.audioIndex > 0 ? this.data.audioIndex - 1 : this.data.audioList.length - 1;
    this.setData({
      audioIndex: audioIndex,
      playStatus: false,
      progress: 0,
      progressText: "00:00",
      durationText: "00:00"
    })
    setTimeout(function () {
      this.playMusic();
    }.bind(this), 1000);
  },

  //播放按钮
  playOrpause: function () {
    let manager = wx.getBackgroundAudioManager();
    if (this.data.playStatus) {
      manager.pause();
    } else {
      manager.play();
    }
  },

  //下一首
  nextMusic: function () {
    let audioIndex = this.data.audioIndex < this.data.audioList.length - 1 ? this.data.audioIndex + 1 : 0;
    this.setData({
      audioIndex: audioIndex,
      playStatus: false,
      progress: 0,
      progressText: "00:00",
      durationText: "00:00"
    })
    setTimeout(function () {
      this.playMusic();
    }.bind(this), 1000);
  },

  //界面切换
  pageChange: function () {
    this.setData({
      showList: true
    })
  },

  //格式化时长
  formatTime: function (s) {
    let t = '';
    s = Math.floor(s);
    if (s > -1) {
      let min = Math.floor(s / 60) % 60;
      let sec = s % 60;
      if (min < 10) {
        t += "0";
      }
      t += min + ":";
      if (sec < 10) {
        t += "0";
      }
      t += sec;
    }
    return t;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  //用户点击右上角分享朋友圈
	onShareTimeline: function () {
		return {
	      title: '遇见0和1',
	      query: {},
	      imageUrl: 'https://s2.loli.net/2023/05/21/4DrEK1gw3IcHl79.gif'
	  }
	},
  /**
   * 用户点击右上角分享好友
   */
  onShareAppMessage: function () {
    return {
      title:'遇见0和1',
      path: '/pages/home/index/index',
      imageUrl: 'https://s2.loli.net/2023/05/21/4DrEK1gw3IcHl79.gif',
    }
  }
})